// 武器强化和技能系统
class WeaponEnhancementSystem {
    constructor() {
        this.weaponMods = {}; // 武器改造
        this.playerSkills = {}; // 玩家技能
        this.experience = 0; // 经验值
        this.skillPoints = 0; // 技能点
        this.weaponStats = {}; // 武器统计数据
        
        this.modDefinitions = this.createModDefinitions();
        this.skillDefinitions = this.createSkillDefinitions();
        
        this.loadProgress();
    }
    
    createModDefinitions() {
        return {
            // 枪管改造
            extendedBarrel: {
                name: '延长枪管',
                description: '增加射程和精度',
                icon: '🔫',
                type: 'barrel',
                effects: {
                    range: 1.5,
                    accuracy: 0.8,
                    damage: 1.1
                },
                cost: 100,
                prerequisites: []
            },
            
            suppressedBarrel: {
                name: '消音器',
                description: '减少噪音，增加暴击率',
                icon: '🔇',
                type: 'barrel',
                effects: {
                    criticalChance: 0.15,
                    stealth: true,
                    damage: 0.9
                },
                cost: 150,
                prerequisites: []
            },
            
            // 弹药改造
            armorPiercing: {
                name: '穿甲弹',
                description: '子弹可以穿透敌人',
                icon: '🏹',
                type: 'ammo',
                effects: {
                    penetration: true,
                    damage: 1.2
                },
                cost: 200,
                prerequisites: []
            },
            
            incendiaryRounds: {
                name: '燃烧弹',
                description: '造成持续火焰伤害',
                icon: '🔥',
                type: 'ammo',
                effects: {
                    fireDamage: 5,
                    burnDuration: 3000
                },
                cost: 180,
                prerequisites: []
            },
            
            explosiveRounds: {
                name: '爆炸弹',
                description: '击中时造成范围伤害',
                icon: '💥',
                type: 'ammo',
                effects: {
                    explosionRadius: 50,
                    explosionDamage: 0.5
                },
                cost: 250,
                prerequisites: ['armorPiercing']
            },
            
            // 瞄准系统
            laserSight: {
                name: '激光瞄准',
                description: '大幅提升精度',
                icon: '🎯',
                type: 'sight',
                effects: {
                    accuracy: 0.6,
                    criticalChance: 0.1
                },
                cost: 120,
                prerequisites: []
            },
            
            thermalScope: {
                name: '热成像瞄准镜',
                description: '透视敌人，增加伤害',
                icon: '👁️',
                type: 'sight',
                effects: {
                    xrayVision: true,
                    damage: 1.15,
                    range: 1.3
                },
                cost: 300,
                prerequisites: ['laserSight']
            },
            
            // 弹夹改造
            extendedMag: {
                name: '扩容弹夹',
                description: '增加弹药容量',
                icon: '📦',
                type: 'magazine',
                effects: {
                    magazineSize: 2,
                    totalAmmo: 1.5
                },
                cost: 100,
                prerequisites: []
            },
            
            quickReload: {
                name: '快速装弹',
                description: '减少换弹时间',
                icon: '⚡',
                type: 'magazine',
                effects: {
                    reloadSpeed: 2,
                    fireRate: 1.1
                },
                cost: 130,
                prerequisites: []
            },
            
            // 特殊改造
            dualWield: {
                name: '双持',
                description: '可以双持武器，射速翻倍',
                icon: '🔫🔫',
                type: 'special',
                effects: {
                    dualWield: true,
                    fireRate: 2,
                    accuracy: 0.7
                },
                cost: 400,
                prerequisites: ['quickReload', 'extendedMag']
            },
            
            smartBullets: {
                name: '智能子弹',
                description: '子弹自动锁定最近敌人',
                icon: '🤖',
                type: 'special',
                effects: {
                    autoAim: true,
                    damage: 1.3,
                    homingRange: 100
                },
                cost: 500,
                prerequisites: ['thermalScope', 'explosiveRounds']
            }
        };
    }
    
    createSkillDefinitions() {
        return {
            // 战斗技能树
            combatTree: {
                name: '战斗专精',
                icon: '⚔️',
                skills: {
                    weaponMastery: {
                        name: '武器精通',
                        description: '所有武器伤害+10%',
                        icon: '🎯',
                        maxLevel: 5,
                        effects: (level) => ({ damageMultiplier: 1 + level * 0.1 }),
                        cost: (level) => level * 2
                    },
                    
                    rapidFire: {
                        name: '连射精通',
                        description: '射击速度+15%',
                        icon: '🔥',
                        maxLevel: 4,
                        effects: (level) => ({ fireRateMultiplier: 1 + level * 0.15 }),
                        cost: (level) => level * 3,
                        prerequisites: ['weaponMastery']
                    },
                    
                    criticalStrike: {
                        name: '致命打击',
                        description: '暴击率+5%，暴击伤害+25%',
                        icon: '💀',
                        maxLevel: 3,
                        effects: (level) => ({ 
                            criticalChance: level * 0.05,
                            criticalDamage: 1.5 + level * 0.25
                        }),
                        cost: (level) => level * 4,
                        prerequisites: ['rapidFire']
                    },
                    
                    berserker: {
                        name: '狂战士',
                        description: '血量越低，伤害越高',
                        icon: '😡',
                        maxLevel: 1,
                        effects: (level) => ({ berserkerMode: true }),
                        cost: (level) => 10,
                        prerequisites: ['criticalStrike']
                    }
                }
            },
            
            // 生存技能树
            survivalTree: {
                name: '生存专家',
                icon: '🛡️',
                skills: {
                    toughness: {
                        name: '坚韧',
                        description: '最大生命值+20',
                        icon: '❤️',
                        maxLevel: 5,
                        effects: (level) => ({ bonusHealth: level * 20 }),
                        cost: (level) => level * 2
                    },
                    
                    regeneration: {
                        name: '生命恢复',
                        description: '每秒恢复1点生命',
                        icon: '💚',
                        maxLevel: 3,
                        effects: (level) => ({ regenRate: level }),
                        cost: (level) => level * 3,
                        prerequisites: ['toughness']
                    },
                    
                    mobility: {
                        name: '敏捷',
                        description: '移动速度+15%',
                        icon: '🏃',
                        maxLevel: 4,
                        effects: (level) => ({ speedMultiplier: 1 + level * 0.15 }),
                        cost: (level) => level * 2,
                        prerequisites: ['toughness']
                    },
                    
                    evasion: {
                        name: '闪避',
                        description: '10%概率闪避攻击',
                        icon: '🌪️',
                        maxLevel: 2,
                        effects: (level) => ({ dodgeChance: level * 0.1 }),
                        cost: (level) => level * 5,
                        prerequisites: ['mobility', 'regeneration']
                    }
                }
            },
            
            // 技术技能树
            techTree: {
                name: '科技专家',
                icon: '🔬',
                skills: {
                    efficiency: {
                        name: '效率提升',
                        description: '换弹速度+25%',
                        icon: '⚡',
                        maxLevel: 4,
                        effects: (level) => ({ reloadSpeedMultiplier: 1 + level * 0.25 }),
                        cost: (level) => level * 2
                    },
                    
                    scanner: {
                        name: '敌人扫描',
                        description: '显示敌人血量和类型',
                        icon: '📡',
                        maxLevel: 1,
                        effects: (level) => ({ enemyScanner: true }),
                        cost: (level) => 5,
                        prerequisites: ['efficiency']
                    },
                    
                    techMastery: {
                        name: '科技精通',
                        description: '武器改造成本-20%',
                        icon: '🔧',
                        maxLevel: 3,
                        effects: (level) => ({ modCostReduction: level * 0.2 }),
                        cost: (level) => level * 3,
                        prerequisites: ['scanner']
                    },
                    
                    overcharge: {
                        name: '过载模式',
                        description: '短时间内武器性能翻倍',
                        icon: '⚡💥',
                        maxLevel: 1,
                        effects: (level) => ({ overchargeMode: true }),
                        cost: (level) => 12,
                        prerequisites: ['techMastery']
                    }
                }
            }
        };
    }
    
    // 经验和技能点管理
    addExperience(amount) {
        this.experience += amount;
        const newSkillPoints = Math.floor(this.experience / 100);
        const gainedPoints = newSkillPoints - this.skillPoints;
        
        if (gainedPoints > 0) {
            this.skillPoints = newSkillPoints;
            this.showSkillPointNotification(gainedPoints);
        }
        
        this.saveProgress();
    }
    
    showSkillPointNotification(points) {
        const notification = document.createElement('div');
        notification.className = 'skill-point-notification';
        notification.innerHTML = `
            <div class="skill-point-content">
                <div class="skill-point-icon">⭐</div>
                <div class="skill-point-text">
                    <h3>技能点获得！</h3>
                    <p>+${points} 技能点</p>
                </div>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            if (notification.parentNode) {
                notification.classList.add('hide');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 600);
            }
        }, 3000);
        
        this.addSkillPointStyles();
    }
    
    addSkillPointStyles() {
        if (document.getElementById('skillPointStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'skillPointStyles';
        styles.textContent = `
            .skill-point-notification {
                position: fixed;
                top: 20px;
                left: 20px;
                background: linear-gradient(135deg, rgba(0, 255, 136, 0.95), rgba(46, 204, 113, 0.95));
                color: #fff;
                padding: 20px 25px;
                border-radius: 12px;
                border: 2px solid #00ff88;
                box-shadow: 0 15px 35px rgba(0, 255, 136, 0.4);
                z-index: 9999;
                animation: skillPointSlide 0.6s ease-out;
            }
            
            .skill-point-notification.hide {
                animation: skillPointSlideOut 0.6s ease-in;
            }
            
            .skill-point-content {
                display: flex;
                align-items: center;
                gap: 15px;
            }
            
            .skill-point-icon {
                font-size: 32px;
                animation: skillPointSpin 2s linear infinite;
            }
            
            @keyframes skillPointSlide {
                0% { transform: translateX(-100%); opacity: 0; }
                100% { transform: translateX(0); opacity: 1; }
            }
            
            @keyframes skillPointSlideOut {
                0% { transform: translateX(0); opacity: 1; }
                100% { transform: translateX(-100%); opacity: 0; }
            }
            
            @keyframes skillPointSpin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        
        document.head.appendChild(styles);
    }
    
    // 武器改造系统
    addModToWeapon(weaponId, modKey) {
        const mod = this.modDefinitions[modKey];
        if (!mod) return false;
        
        // 检查前置条件
        if (mod.prerequisites.length > 0) {
            const hasPrerequisites = mod.prerequisites.every(prereq => 
                this.weaponMods[weaponId] && this.weaponMods[weaponId].includes(prereq)
            );
            if (!hasPrerequisites) return false;
        }
        
        // 检查货币
        if (window.roguelikeSystem && !window.roguelikeSystem.spendCurrency(mod.cost)) {
            return false;
        }
        
        // 添加改造
        this.weaponMods[weaponId] = this.weaponMods[weaponId] || [];
        if (!this.weaponMods[weaponId].includes(modKey)) {
            this.weaponMods[weaponId].push(modKey);
            this.applyModToWeapon(weaponId, mod);
            this.saveProgress();
            return true;
        }
        
        return false;
    }
    
    applyModToWeapon(weaponId, mod) {
        if (!window.player || !window.player.currentWeapon) return;
        
        const weapon = window.player.currentWeapon;
        
        // 应用改造效果
        Object.entries(mod.effects).forEach(([effect, value]) => {
            switch (effect) {
                case 'damage':
                    weapon.damage = Math.floor(weapon.damage * value);
                    break;
                case 'fireRate':
                    weapon.fireRate = weapon.fireRate / value;
                    break;
                case 'accuracy':
                    weapon.accuracy = (weapon.accuracy || 1) * value;
                    break;
                case 'magazineSize':
                    weapon.currentAmmo = Math.floor(weapon.currentAmmo * value);
                    break;
                case 'totalAmmo':
                    weapon.totalAmmo = Math.floor(weapon.totalAmmo * value);
                    break;
                case 'penetration':
                    weapon.penetration = value;
                    break;
                case 'explosionRadius':
                    weapon.explosionRadius = value;
                    break;
                case 'fireDamage':
                    weapon.fireDamage = value;
                    break;
            }
        });
        
        console.log(`武器改造应用: ${mod.name}`);
    }
    
    // 技能系统
    learnSkill(treeKey, skillKey) {
        console.log(`尝试学习技能: ${treeKey}.${skillKey}`);
        
        const tree = this.skillDefinitions[treeKey];
        if (!tree) {
            console.error(`找不到技能树: ${treeKey}`);
            return false;
        }
        
        const skill = tree.skills[skillKey];
        if (!skill) {
            console.error(`找不到技能: ${skillKey}`);
            return false;
        }
        
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        console.log(`当前等级: ${currentLevel}, 最大等级: ${skill.maxLevel}`);
        
        if (currentLevel >= skill.maxLevel) {
            console.log('技能已达到最大等级');
            return false;
        }
        
        const cost = skill.cost(currentLevel + 1);
        console.log(`技能消耗: ${cost}, 当前技能点: ${this.skillPoints}`);
        
        if (this.skillPoints < cost) {
            console.log('技能点不足');
            return false;
        }
        
        // 检查前置条件
        if (skill.prerequisites && skill.prerequisites.length > 0) {
            const hasPrerequisites = skill.prerequisites.every(prereq => {
                const prereqLevel = this.getSkillLevel(treeKey, prereq);
                console.log(`前置技能 ${prereq} 等级: ${prereqLevel}`);
                return prereqLevel > 0;
            });
            if (!hasPrerequisites) {
                console.log('不满足前置条件');
                return false;
            }
        }
        
        // 学习技能
        this.skillPoints -= cost;
        this.playerSkills[treeKey] = this.playerSkills[treeKey] || {};
        this.playerSkills[treeKey][skillKey] = currentLevel + 1;
        
        console.log(`成功学习技能: ${skill.name} (等级 ${currentLevel + 1})`);
        console.log(`剩余技能点: ${this.skillPoints}`);
        
        this.applySkillEffects();
        this.saveProgress();
        
        return true;
    }
    
    getSkillLevel(treeKey, skillKey) {
        return (this.playerSkills[treeKey] && this.playerSkills[treeKey][skillKey]) || 0;
    }
    
    applySkillEffects() {
        if (!window.player) return;
        
        let totalEffects = {
            damageMultiplier: 1,
            fireRateMultiplier: 1,
            speedMultiplier: 1,
            reloadSpeedMultiplier: 1,
            bonusHealth: 0,
            regenRate: 0,
            criticalChance: 0,
            criticalDamage: 1.5,
            dodgeChance: 0,
            modCostReduction: 0
        };
        
        // 计算所有技能效果
        Object.entries(this.playerSkills).forEach(([treeKey, skills]) => {
            Object.entries(skills).forEach(([skillKey, level]) => {
                const skill = this.skillDefinitions[treeKey].skills[skillKey];
                if (skill && level > 0) {
                    const effects = skill.effects(level);
                    Object.entries(effects).forEach(([effect, value]) => {
                        if (typeof value === 'number') {
                            if (effect.includes('Multiplier')) {
                                totalEffects[effect] *= value;
                            } else {
                                totalEffects[effect] += value;
                            }
                        } else {
                            totalEffects[effect] = value;
                        }
                    });
                }
            });
        });
        
        // 应用效果到玩家
        window.player.baseMaxHealth = window.player.baseMaxHealth || window.player.maxHealth;
        window.player.maxHealth = window.player.baseMaxHealth + totalEffects.bonusHealth;
        
        window.player.baseSpeed = window.player.baseSpeed || window.player.speed;
        window.player.speed = window.player.baseSpeed * totalEffects.speedMultiplier;
        
        // 应用武器效果
        if (window.player.currentWeapon) {
            const weapon = window.player.currentWeapon;
            weapon.baseDamage = weapon.baseDamage || weapon.damage;
            weapon.damage = Math.floor(weapon.baseDamage * totalEffects.damageMultiplier);
            
            weapon.baseFireRate = weapon.baseFireRate || weapon.fireRate;
            weapon.fireRate = weapon.baseFireRate / totalEffects.fireRateMultiplier;
        }
        
        // 启动生命恢复
        if (totalEffects.regenRate > 0) {
            this.startHealthRegeneration(totalEffects.regenRate);
        }
        
        // 存储效果供其他系统使用
        this.activeSkillEffects = totalEffects;
    }
    
    startHealthRegeneration(rate) {
        if (this.regenInterval) return;
        
        this.regenInterval = setInterval(() => {
            if (window.player && window.player.health < window.player.maxHealth) {
                window.player.health = Math.min(window.player.maxHealth, window.player.health + rate);
                window.player.updateHealthUI();
            }
        }, 1000);
    }
    
    // 武器统计追踪
    trackWeaponUsage(weaponType, action, value = 1) {
        this.weaponStats[weaponType] = this.weaponStats[weaponType] || {
            shotsfired: 0,
            hits: 0,
            kills: 0,
            damage: 0,
            timeUsed: 0
        };
        
        this.weaponStats[weaponType][action] += value;
        this.saveProgress();
    }
    
    // 保存和加载
    saveProgress() {
        const saveData = {
            weaponMods: this.weaponMods,
            playerSkills: this.playerSkills,
            experience: this.experience,
            skillPoints: this.skillPoints,
            weaponStats: this.weaponStats
        };
        
        localStorage.setItem('zombieGameWeaponEnhancement', JSON.stringify(saveData));
    }
    
    loadProgress() {
        const saved = localStorage.getItem('zombieGameWeaponEnhancement');
        if (saved) {
            const data = JSON.parse(saved);
            this.weaponMods = data.weaponMods || {};
            this.playerSkills = data.playerSkills || {};
            this.experience = data.experience || 0;
            this.skillPoints = data.skillPoints || 0;
            this.weaponStats = data.weaponStats || {};
        }
        
        // 给玩家一些初始技能点进行测试
        if (this.skillPoints === 0) {
            this.skillPoints = 25;
            this.experience = 3000;
            this.saveProgress();
            console.log('初始化技能点和经验值，用于测试');
        }
        
        console.log(`加载完成 - 技能点: ${this.skillPoints}, 经验: ${this.experience}`);
    }
    
    // 获取可用的改造
    getAvailableMods(weaponId) {
        const currentMods = this.weaponMods[weaponId] || [];
        
        return Object.entries(this.modDefinitions).filter(([key, mod]) => {
            // 已经拥有的改造
            if (currentMods.includes(key)) return false;
            
            // 检查前置条件
            if (mod.prerequisites.length > 0) {
                return mod.prerequisites.every(prereq => currentMods.includes(prereq));
            }
            
            return true;
        });
    }
    
    // 已删除旧的createSkillTreeUI方法，使用新的系统
    
    buildSkillTreeHTML(treeKey, tree) {
        console.log(`构建技能树: ${treeKey} - ${tree.name}`);
        
        const skillsHTML = Object.entries(tree.skills)
            .map(([skillKey, skill]) => this.buildSkillHTML(treeKey, skillKey, skill))
            .join('');
        
        return `
            <div class="skill-tree" data-tree="${treeKey}">
                <h3 class="skill-tree-title">
                    <span class="skill-tree-icon">${tree.icon}</span>
                    ${tree.name}
                </h3>
                <div class="skill-tree-skills">
                    ${skillsHTML}
                </div>
            </div>
        `;
    }
    
    buildSkillHTML(treeKey, skillKey, skill) {
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        const isMaxLevel = currentLevel >= skill.maxLevel;
        const cost = isMaxLevel ? 0 : skill.cost(currentLevel + 1);
        const canAfford = this.skillPoints >= cost;
        const hasPrerequisites = !skill.prerequisites || skill.prerequisites.every(prereq => this.getSkillLevel(treeKey, prereq) > 0);
        const canLearn = canAfford && hasPrerequisites && !isMaxLevel;
        
        console.log(`构建技能: ${skillKey}, 当前等级: ${currentLevel}, 可学习: ${canLearn}`);
        
        let statusClass = '';
        if (isMaxLevel) statusClass = 'max-level';
        else if (canLearn) statusClass = 'available';
        else statusClass = 'locked';
        
        const learnButton = canLearn ? 
            `<button class="learn-skill-btn" data-tree="${treeKey}" data-skill="${skillKey}" type="button">
                ✨ 学习 (耗费: ${cost}点)
            </button>` : 
            `<div class="skill-locked-info">
                ${isMaxLevel ? '✅ 已满级' : 
                  (!canAfford ? `❌ 技能点不足 (需要${cost}点)` : 
                   '❌ 前置条件不满足')}
            </div>`;
        
        return `
            <div class="skill-node ${statusClass}" data-tree="${treeKey}" data-skill="${skillKey}">
                <div class="skill-icon">${skill.icon}</div>
                <div class="skill-info">
                    <h4 class="skill-name">${skill.name}</h4>
                    <p class="skill-description">${skill.description}</p>
                    <div class="skill-level">等级: ${currentLevel}/${skill.maxLevel}</div>
                    <div class="skill-cost">
                        ${isMaxLevel ? '已满级' : `消耗: ${cost} 技能点`}
                    </div>
                </div>
                ${learnButton}
            </div>
        `;
    }
    
    // 绑定技能树事件
    bindSkillTreeEvents() {
        console.log('🔗 开始绑定技能树事件...');
        
        // 绑定返回按钮
        this.bindReturnButton();
        
        // 绑定重置按钮
        this.bindResetButton();
        
        // 绑定学习按钮
        this.bindLearnButtons();
        
        console.log('✅ 技能树事件绑定完成');
    }
    
    // 绑定返回按钮
    bindReturnButton() {
        const skillTreeBack = document.getElementById('skillTreeBack');
        if (skillTreeBack) {
            // 移除旧的事件监听器
            if (skillTreeBack._skillTreeBackHandler) {
                skillTreeBack.removeEventListener('click', skillTreeBack._skillTreeBackHandler);
            }
            
            // 创建新的事件处理器
            skillTreeBack._skillTreeBackHandler = (e) => {
                console.log('🔙 技能树返回按钮被点击');
                e.preventDefault();
                e.stopPropagation();
                
                // 调用主游戏的方法返回主菜单
                if (window.game) {
                    window.game.hideAllMenus();
                    window.game.showMenu('startMenu');
                    console.log('✅ 已返回主菜单');
                } else {
                    console.error('❌ 找不到游戏实例');
                }
            };
            
            skillTreeBack.addEventListener('click', skillTreeBack._skillTreeBackHandler);
            console.log('✅ 返回按钮绑定成功');
        } else {
            console.warn('⚠️ 找不到返回按钮');
        }
    }
    
    // 绑定重置按钮
    bindResetButton() {
        const resetSkillsBtn = document.getElementById('resetSkillsBtn');
        if (resetSkillsBtn) {
            // 移除旧的事件监听器
            if (resetSkillsBtn._skillTreeResetHandler) {
                resetSkillsBtn.removeEventListener('click', resetSkillsBtn._skillTreeResetHandler);
            }
            
            // 创建新的事件处理器
            resetSkillsBtn._skillTreeResetHandler = (e) => {
                console.log('🔄 技能重置按钮被点击');
                e.preventDefault();
                e.stopPropagation();
                
                this.resetAllSkills();
            };
            
            resetSkillsBtn.addEventListener('click', resetSkillsBtn._skillTreeResetHandler);
            console.log('✅ 重置按钮绑定成功');
        } else {
            console.warn('⚠️ 找不到重置按钮');
        }
    }
    
    // 绑定学习按钮
    bindLearnButtons() {
        const skillTreeContainer = document.getElementById('skillTreeContainer');
        if (!skillTreeContainer) {
            console.error('找不到技能树容器，无法绑定事件');
            return;
        }
        
        // 移除所有旧的事件监听器
        if (this.skillTreeClickHandler) {
            skillTreeContainer.removeEventListener('click', this.skillTreeClickHandler);
        }
        
        // 创建新的事件处理器 - 专门处理学习按钮
        this.skillTreeClickHandler = (e) => {
            // 检查是否点击了学习按钮
            let learnButton = null;
            
            if (e.target.classList.contains('learn-skill-btn')) {
                learnButton = e.target;
            } else {
                learnButton = e.target.closest('.learn-skill-btn');
            }
            
            if (learnButton) {
                console.log('✅ 检测到学习按钮点击:', learnButton);
                e.preventDefault();
                e.stopPropagation();
                
                // 获取技能数据
                const treeKey = learnButton.getAttribute('data-tree') || learnButton.dataset.tree;
                const skillKey = learnButton.getAttribute('data-skill') || learnButton.dataset.skill;
                
                console.log(`🎯 点击学习按钮: ${treeKey}.${skillKey}`);
                console.log(`💰 当前技能点: ${this.skillPoints}`);
                
                // 防抖处理
                if (this.lastClickTime && Date.now() - this.lastClickTime < 500) {
                    console.log('⚠️ 点击过于频繁，忽略此次点击');
                    return;
                }
                this.lastClickTime = Date.now();
                
                // 处理技能学习
                this.handleSkillLearn(treeKey, skillKey, learnButton);
            }
        };
        
        // 绑定事件监听器
        skillTreeContainer.addEventListener('click', this.skillTreeClickHandler);
        
        // 直接绑定到所有学习按钮作为备用
        this.bindDirectButtonEvents();
        
        console.log('✅ 学习按钮事件绑定完成');
    }
    
    // 额外的直接按钮绑定
    bindDirectButtonEvents() {
        const learnButtons = document.querySelectorAll('.learn-skill-btn');
        console.log(`🔗 直接绑定 ${learnButtons.length} 个学习按钮`);
        
        learnButtons.forEach((button, index) => {
            // 移除旧的事件监听器
            if (button._directClickHandler) {
                button.removeEventListener('click', button._directClickHandler);
            }
            
            // 创建新的直接事件处理器
            button._directClickHandler = (e) => {
                console.log(`🎯 直接按钮点击: 按钮${index + 1}`);
                e.stopPropagation();
                e.preventDefault();
                
                const treeKey = button.getAttribute('data-tree') || button.dataset.tree;
                const skillKey = button.getAttribute('data-skill') || button.dataset.skill;
                
                console.log(`📊 技能数据: ${treeKey}.${skillKey}`);
                
                this.handleSkillLearn(treeKey, skillKey, button);
            };
            
            // 绑定直接事件监听器
            button.addEventListener('click', button._directClickHandler);
        });
    }
    
    // 测试事件绑定
    testEventBinding() {
        const learnButtons = document.querySelectorAll('.learn-skill-btn');
        console.log(`🔍 找到 ${learnButtons.length} 个学习按钮`);
        
        learnButtons.forEach((button, index) => {
            console.log(`按钮 ${index + 1}:`, {
                treeKey: button.dataset.tree,
                skillKey: button.dataset.skill,
                visible: button.offsetParent !== null,
                enabled: !button.disabled,
                hasDirectHandler: !!button._directClickHandler
            });
        });
    }
    
    // 处理技能学习
    handleSkillLearn(treeKey, skillKey, button) {
        console.log(`开始处理技能学习: ${treeKey}.${skillKey}`);
        
        // 检查数据有效性
        if (!treeKey || !skillKey) {
            console.error('技能数据无效:', { treeKey, skillKey });
            this.showTemporaryMessage('技能数据错误', 'error');
            return;
        }
        
        // 添加点击特效
        this.addButtonClickEffect(button);
        
        console.log('开始调用learnSkill方法...');
        
        // 尝试学习技能
        const result = this.learnSkill(treeKey, skillKey);
        
        console.log(`learnSkill返回结果: ${result}`);
        
        if (result) {
            console.log(`✅ 成功学习技能: ${treeKey}.${skillKey}`);
            
            // 显示成功消息
            this.showSkillLearnSuccessMessage(treeKey, skillKey);
            
            // 更新UI（更短的延迟）
            setTimeout(() => {
                console.log('开始更新技能树UI...');
                this.initializeSkillTreeUI();
            }, 300);
        } else {
            console.log(`❌ 学习技能失败: ${treeKey}.${skillKey}`);
            this.showSkillLearnFailMessage(treeKey, skillKey);
        }
    }
    
    // 添加按钮点击特效
    addButtonClickEffect(button) {
        if (!button) return;
        
        console.log('添加按钮点击特效');
        button.style.transition = 'all 0.1s ease';
        button.style.transform = 'scale(0.95)';
        button.style.backgroundColor = '#45a049';
        button.style.boxShadow = '0 0 15px rgba(76, 175, 80, 0.8)';
        
        setTimeout(() => {
            button.style.transform = '';
            button.style.backgroundColor = '';
            button.style.boxShadow = '';
        }, 200);
    }
    
    // 显示技能学习成功消息
    showSkillLearnSuccessMessage(treeKey, skillKey) {
        const skill = this.skillDefinitions[treeKey].skills[skillKey];
        const message = `✅ 学习成功: ${skill.name}`;
        
        this.showTemporaryMessage(message, 'success');
    }
    
    // 显示技能学习失败消息
    showSkillLearnFailMessage(treeKey, skillKey) {
        const skill = this.skillDefinitions[treeKey].skills[skillKey];
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        const cost = skill.cost(currentLevel + 1);
        
        let message = `❌ 无法学习 ${skill.name}: `;
        
        if (currentLevel >= skill.maxLevel) {
            message += '已达到最高等级';
        } else if (this.skillPoints < cost) {
            message += `技能点不足（需要${cost}点）`;
        } else {
            message += '不满足前置条件';
        }
        
        this.showTemporaryMessage(message, 'error');
    }
    
    // 显示临时消息
    showTemporaryMessage(text, type = 'info') {
        const messageDiv = document.createElement('div');
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            z-index: 10000;
            background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            animation: slideInRight 0.3s ease-out;
        `;
        messageDiv.textContent = text;
        
        document.body.appendChild(messageDiv);
        
        // 添加动画样式
        if (!document.getElementById('messageAnimationStyles')) {
            const animationStyles = document.createElement('style');
            animationStyles.id = 'messageAnimationStyles';
            animationStyles.textContent = `
                @keyframes slideInRight {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
                @keyframes slideOutRight {
                    from { transform: translateX(0); opacity: 1; }
                    to { transform: translateX(100%); opacity: 0; }
                }
            `;
            document.head.appendChild(animationStyles);
        }
        
        setTimeout(() => {
            messageDiv.style.animation = 'slideOutRight 0.3s ease-in';
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 300);
        }, 2000);
    }
    
    // 更新技能树UI
    updateSkillTreeUI() {
        const skillMenu = document.getElementById('skillTreeMenu');
        if (skillMenu) {
            const container = skillMenu.querySelector('.skill-info');
            if (container) {
                container.innerHTML = `
                    <div class="skill-stat">
                        <span class="skill-stat-label">经验值:</span>
                        <span class="skill-stat-value">${this.experience}</span>
                    </div>
                    <div class="skill-stat">
                        <span class="skill-stat-label">技能点:</span>
                        <span class="skill-stat-value">${this.skillPoints}</span>
                    </div>
                `;
            }
            
            // 更新技能树
            const skillTrees = skillMenu.querySelector('.skill-trees');
            if (skillTrees) {
                skillTrees.innerHTML = Object.entries(this.skillDefinitions).map(([treeKey, tree]) => this.createSkillTreeHTML(treeKey, tree)).join('');
                this.addSkillLearnListeners(skillMenu);
            }
        }
    }
    
    // 显示技能学习错误信息
    showSkillErrorMessage(treeKey, skillKey) {
        const skill = this.skillDefinitions[treeKey].skills[skillKey];
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        const cost = skill.cost(currentLevel + 1);
        const hasPrerequisites = !skill.prerequisites || skill.prerequisites.every(prereq => this.getSkillLevel(treeKey, prereq) > 0);
        
        let message = '无法学习该技能：';
        let icon = '⚠️';
        
        if (currentLevel >= skill.maxLevel) {
            message += '已达到最高等级';
            icon = '✅';
        } else if (this.skillPoints < cost) {
            message += `技能点不足，需要 ${cost} 点`;
            icon = '💰';
        } else if (!hasPrerequisites) {
            message += '前置技能未学习';
            icon = '🔒';
        }
        
        // 创建增强的错误提示
        const errorDiv = document.createElement('div');
        errorDiv.className = 'skill-error-message enhanced';
        errorDiv.innerHTML = `
            <div class="error-content">
                <div class="error-icon">${icon}</div>
                <div class="error-text">${message}</div>
            </div>
        `;
        errorDiv.style.cssText = `
            position: fixed;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: linear-gradient(135deg, rgba(255, 0, 0, 0.95), rgba(220, 20, 60, 0.95));
            color: white;
            padding: 20px 30px;
            border-radius: 15px;
            z-index: 15000;
            font-size: 16px;
            box-shadow: 
                0 15px 40px rgba(255, 0, 0, 0.4),
                inset 0 1px 0 rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            animation: errorShake 0.6s ease-out;
        `;
        
        document.body.appendChild(errorDiv);
        
        // 添加错误动画样式
        if (!document.getElementById('errorShakeStyles')) {
            const styles = document.createElement('style');
            styles.id = 'errorShakeStyles';
            styles.textContent = `
                .error-content {
                    display: flex;
                    align-items: center;
                    gap: 15px;
                }
                .error-icon {
                    font-size: 24px;
                    animation: iconBounce 0.6s ease-out;
                }
                .error-text {
                    font-weight: bold;
                    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
                }
                @keyframes errorShake {
                    0%, 100% { transform: translate(-50%, -50%); }
                    25% { transform: translate(-52%, -50%); }
                    75% { transform: translate(-48%, -50%); }
                }
                @keyframes iconBounce {
                    0%, 100% { transform: scale(1); }
                    50% { transform: scale(1.2); }
                }
            `;
            document.head.appendChild(styles);
        }
        
        // 2.5秒后自动移除
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.style.animation = 'fadeOut 0.4s ease-in';
                setTimeout(() => {
                    if (errorDiv.parentNode) {
                        document.body.removeChild(errorDiv);
                    }
                }, 400);
            }
        }, 2500);
    }
    
    // 显示技能学习成功
    showSkillLearnSuccess(treeKey, skillKey) {
        const skill = this.skillDefinitions[treeKey].skills[skillKey];
        const currentLevel = this.getSkillLevel(treeKey, skillKey);
        
        const successDiv = document.createElement('div');
        successDiv.className = 'skill-success-message';
        successDiv.innerHTML = `
            <div class="success-content">
                <div class="success-icon">✨</div>
                <div class="success-text">
                    <div class="success-title">技能升级！</div>
                    <div class="success-skill">${skill.name} Lv.${currentLevel}</div>
                </div>
            </div>
        `;
        successDiv.style.cssText = `
            position: fixed;
            top: 25%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: linear-gradient(135deg, rgba(0, 255, 136, 0.95), rgba(46, 204, 113, 0.95));
            color: white;
            padding: 25px 35px;
            border-radius: 15px;
            z-index: 15000;
            font-size: 16px;
            box-shadow: 
                0 15px 40px rgba(0, 255, 136, 0.4),
                inset 0 1px 0 rgba(255, 255, 255, 0.3);
            border: 2px solid rgba(255, 255, 255, 0.3);
            animation: successPop 0.8s ease-out;
        `;
        
        document.body.appendChild(successDiv);
        
        // 添加成功动画样式
        if (!document.getElementById('successPopStyles')) {
            const styles = document.createElement('style');
            styles.id = 'successPopStyles';
            styles.textContent = `
                .success-content {
                    display: flex;
                    align-items: center;
                    gap: 15px;
                }
                .success-icon {
                    font-size: 28px;
                    animation: successGlow 0.8s ease-out;
                }
                .success-title {
                    font-weight: bold;
                    font-size: 18px;
                    margin-bottom: 5px;
                }
                .success-skill {
                    font-size: 14px;
                    opacity: 0.9;
                }
                @keyframes successPop {
                    0% {
                        opacity: 0;
                        transform: translate(-50%, -50%) scale(0.5);
                    }
                    70% {
                        opacity: 1;
                        transform: translate(-50%, -50%) scale(1.1);
                    }
                    100% {
                        opacity: 1;
                        transform: translate(-50%, -50%) scale(1);
                    }
                }
                @keyframes successGlow {
                    0%, 100% { 
                        text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
                        transform: rotate(0deg);
                    }
                    50% { 
                        text-shadow: 0 0 20px rgba(255, 255, 255, 1);
                        transform: rotate(180deg);
                    }
                }
            `;
            document.head.appendChild(styles);
        }
        
        // 2秒后移除
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.style.animation = 'fadeOut 0.4s ease-in';
                setTimeout(() => {
                    if (successDiv.parentNode) {
                        document.body.removeChild(successDiv);
                    }
                }, 400);
            }
        }, 2000);
    }
    
    // 播放学习按钮特效
    playLearnButtonEffect(button) {
        button.style.transform = 'scale(0.95)';
        button.style.filter = 'brightness(1.2)';
        
        setTimeout(() => {
            button.style.transform = 'scale(1)';
            button.style.filter = 'brightness(1)';
        }, 150);
    }
    
    // 播放按钮悬停特效
    playButtonHoverEffect(button) {
        // 创建悬停粒子
        const particle = document.createElement('div');
        particle.style.cssText = `
            position: absolute;
            top: 50%;
            left: 50%;
            width: 4px;
            height: 4px;
            background: radial-gradient(circle, #00ff88, transparent);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            pointer-events: none;
            z-index: 10;
            animation: buttonParticle 0.8s ease-out;
        `;
        
        button.appendChild(particle);
        
        // 添加粒子动画
        if (!document.getElementById('buttonParticleStyles')) {
            const styles = document.createElement('style');
            styles.id = 'buttonParticleStyles';
            styles.textContent = `
                @keyframes buttonParticle {
                    0% {
                        opacity: 1;
                        transform: translate(-50%, -50%) scale(0);
                    }
                    50% {
                        opacity: 0.8;
                        transform: translate(-50%, -50%) scale(3);
                    }
                    100% {
                        opacity: 0;
                        transform: translate(-50%, -50%) scale(6);
                    }
                }
            `;
            document.head.appendChild(styles);
        }
        
        // 移除粒子
        setTimeout(() => {
            if (particle.parentNode) {
                particle.parentNode.removeChild(particle);
            }
        }, 800);
    }
    
    addSkillTreeStyles() {
        if (document.getElementById('skillTreeStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'skillTreeStyles';
        styles.textContent = `
            .skill-tree-menu {
                max-width: 1200px;
                max-height: 85vh;
                overflow-y: auto;
                padding: 30px;
            }
            
            .skill-info {
                display: flex;
                justify-content: center;
                gap: 30px;
                margin-bottom: 30px;
                padding: 15px;
                background: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
            }
            
            .skill-stat {
                text-align: center;
            }
            
            .skill-stat-label {
                display: block;
                color: #ccc;
                font-size: 12px;
                margin-bottom: 5px;
            }
            
            .skill-stat-value {
                display: block;
                color: #ffd700;
                font-size: 20px;
                font-weight: bold;
            }
            
            .skill-trees {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
                gap: 30px;
                margin-bottom: 30px;
                max-height: 50vh;
                overflow-y: auto;
                padding: 10px;
            }
            
            .skill-tree {
                background: rgba(40, 40, 40, 0.9);
                border-radius: 15px;
                padding: 20px;
                border: 2px solid #555;
            }
            
            .skill-tree-title {
                text-align: center;
                margin-bottom: 20px;
                color: #fff;
                font-size: 18px;
            }
            
            .skill-tree-icon {
                font-size: 24px;
                margin-right: 10px;
            }
            
            .skill-tree-skills {
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            
            .skill-node {
                display: flex;
                align-items: center;
                gap: 15px;
                padding: 15px;
                background: rgba(60, 60, 60, 0.9);
                border-radius: 10px;
                border: 2px solid #666;
                transition: all 0.3s ease;
            }
            
            .skill-node.available {
                border-color: #00ff88;
                box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
            }
            
            .skill-node.max-level {
                border-color: #ffd700;
                background: rgba(255, 215, 0, 0.1);
            }
            
            .skill-node:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            }
            
            .skill-icon {
                font-size: 24px;
                min-width: 30px;
                text-align: center;
            }
            
            .skill-info {
                flex: 1;
            }
            
            .skill-name {
                margin: 0 0 5px 0;
                color: #fff;
                font-size: 14px;
            }
            
            .skill-description {
                margin: 0 0 10px 0;
                color: #ccc;
                font-size: 12px;
                line-height: 1.3;
            }
            
            .skill-level {
                font-size: 11px;
                color: #ffd700;
                margin-bottom: 5px;
            }
            
            .skill-cost {
                font-size: 11px;
                color: #00ff88;
            }
            
            .learn-skill-btn {
                padding: 10px 18px;
                background: linear-gradient(135deg, #00ff88, #4ecdc4);
                border: none;
                border-radius: 8px;
                color: #fff;
                font-size: 12px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
                position: relative;
                overflow: hidden;
                box-shadow: 0 4px 12px rgba(0, 255, 136, 0.2);
            }
            
            .learn-skill-btn::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, 
                    transparent, 
                    rgba(255, 255, 255, 0.4), 
                    transparent
                );
                transition: left 0.6s ease;
            }
            
            .learn-skill-btn:hover {
                transform: translateY(-3px) scale(1.05);
                box-shadow: 
                    0 8px 20px rgba(0, 255, 136, 0.4),
                    0 0 15px rgba(0, 255, 136, 0.3);
                filter: brightness(1.1);
            }
            
            .learn-skill-btn:hover::before {
                left: 100%;
            }
            
            .learn-skill-btn:active {
                transform: translateY(-1px) scale(0.98);
                transition: all 0.1s ease;
            }
            
            .skill-controls {
                text-align: center;
            }
            
            /* 滚动条样式 */
            .skill-tree-menu::-webkit-scrollbar,
            .skill-trees::-webkit-scrollbar {
                width: 8px;
            }
            
            .skill-tree-menu::-webkit-scrollbar-track,
            .skill-trees::-webkit-scrollbar-track {
                background: rgba(40, 40, 40, 0.5);
                border-radius: 10px;
            }
            
            .skill-tree-menu::-webkit-scrollbar-thumb,
            .skill-trees::-webkit-scrollbar-thumb {
                background: linear-gradient(135deg, #ff6b6b, #ff8e53);
                border-radius: 10px;
            }
            
            .skill-tree-menu::-webkit-scrollbar-thumb:hover,
            .skill-trees::-webkit-scrollbar-thumb:hover {
                background: linear-gradient(135deg, #ff8e53, #ffb347);
            }
            
            /* 额外的技能状态样式 */
            .skill-locked-info {
                margin-top: 10px;
                padding: 8px 12px;
                background: rgba(255, 0, 0, 0.1);
                border: 1px solid #ff4444;
                border-radius: 6px;
                font-size: 11px;
                color: #ff6666;
                text-align: center;
                line-height: 1.3;
            }
            
            .skill-node.locked {
                opacity: 0.6;
                border-color: #666;
                background: rgba(100, 100, 100, 0.1);
            }
            
            .skill-node.available {
                animation: availablePulse 2s ease-in-out infinite;
            }
            
            @keyframes availablePulse {
                0%, 100% { 
                    box-shadow: 0 0 8px rgba(76, 175, 80, 0.4);
                }
                50% { 
                    box-shadow: 0 0 20px rgba(76, 175, 80, 0.8);
                }
            }
        `;
        
        document.head.appendChild(styles);
    }
    
    openSkillTree() {
        console.log('🌳 打开技能树');
        
        // 初始化UI
        this.initializeSkillTreeUI();
        
        // 显示菜单
        const skillTreeMenu = document.getElementById('skillTreeMenu');
        if (skillTreeMenu) {
            skillTreeMenu.classList.remove('hidden');
            console.log(`✅ 技能树打开成功 - 当前技能点: ${this.skillPoints}`);
            
            // 进行功能测试
            setTimeout(() => {
                this.performFunctionalityTest();
            }, 500);
        } else {
            console.error('❌ 找不到技能树菜单元素');
        }
    }
    
    // 执行功能测试
    performFunctionalityTest() {
        console.log('🗜️ 执行技能树功能测试...');
        
        const skillTreeContainer = document.getElementById('skillTreeContainer');
        const learnButtons = document.querySelectorAll('.learn-skill-btn');
        const backButton = document.getElementById('skillTreeBack');
        const resetButton = document.getElementById('resetSkillsBtn');
        
        console.log('测试结果:', {
            '技能树容器': skillTreeContainer ? '✅ 存在' : '❌ 不存在',
            '学习按钮数量': learnButtons.length,
            '返回按钮': backButton ? '✅ 存在' : '❌ 不存在',
            '重置按钮': resetButton ? '✅ 存在' : '❌ 不存在',
            '事件监听器': this.skillTreeClickHandler ? '✅ 已绑定' : '❌ 未绑定'
        });
        
        // 测试第一个学习按钮的数据
        if (learnButtons.length > 0) {
            const firstButton = learnButtons[0];
            console.log('第一个学习按钮信息:', {
                'treeKey': firstButton.dataset.tree,
                'skillKey': firstButton.dataset.skill,
                '可见性': firstButton.offsetParent !== null,
                '启用状态': !firstButton.disabled
            });
        }
        
        console.log('🎉 功能测试完成');
    }
    
    // 初始化技能树UI
    initializeSkillTreeUI() {
        // 更新数值显示
        this.updateSkillTreeStats();
        
        // 创建技能树内容
        this.createSkillTreeContent();
    }
    
    // 更新技能树统计数据
    updateSkillTreeStats() {
        const experienceDisplay = document.getElementById('experienceDisplay');
        const skillPointsDisplay = document.getElementById('skillPointsDisplay');
        
        if (experienceDisplay) {
            experienceDisplay.textContent = this.experience;
        }
        if (skillPointsDisplay) {
            skillPointsDisplay.textContent = this.skillPoints;
        }
        
        console.log(`更新技能树统计: 经验=${this.experience}, 技能点=${this.skillPoints}`);
    }
    
    // 创建技能树内容
    createSkillTreeContent() {
        const skillTreeContainer = document.getElementById('skillTreeContainer');
        if (!skillTreeContainer) {
            console.error('找不到技能树容器元素');
            return;
        }
        
        console.log('开始创建技能树内容...');
        
        const skillTreesHTML = Object.entries(this.skillDefinitions)
            .map(([treeKey, tree]) => this.buildSkillTreeHTML(treeKey, tree))
            .join('');
        
        skillTreeContainer.innerHTML = `<div class="skill-trees">${skillTreesHTML}</div>`;
        
        // 添加事件监听器
        this.bindSkillTreeEvents();
        
        // 重新绑定按钮事件监听器
        this.rebindButtonEvents();
        
        // 添加样式
        this.addSkillTreeStyles();
        
        console.log('技能树内容创建完成');
        
        // 显示当前状态
        console.log(`当前技能点: ${this.skillPoints}`);
        console.log(`当前经验: ${this.experience}`);
        console.log(`已学习技能:`, this.playerSkills);
    }
    
    // 重新绑定按钮事件（不影响技能学习按钮）
    rebindButtonEvents() {
        console.log('🔧 重新绑定按钮事件...');
        
        // 确保技能学习按钮事件正常工作
        this.bindDirectButtonEvents();
        
        console.log('✅ 按钮事件检查完成');
    }
    
    // 重置所有技能
    resetAllSkills() {
        if (!confirm('确定要重置所有技能吗？这将返还所有技能点。')) {
            return;
        }
        
        console.log('重置技能树');
        const totalSpentPoints = this.calculateTotalSpentPoints();
        this.playerSkills = {};
        this.skillPoints += totalSpentPoints;
        this.saveProgress();
        this.initializeSkillTreeUI();
        
        this.showTemporaryMessage(`技能重置成功！返还了 ${totalSpentPoints} 个技能点`, 'success');
    }
    
    // 计算已花费的技能点
    calculateTotalSpentPoints() {
        let totalPoints = 0;
        Object.entries(this.playerSkills).forEach(([treeKey, skills]) => {
            Object.entries(skills).forEach(([skillKey, level]) => {
                const skill = this.skillDefinitions[treeKey]?.skills[skillKey];
                if (skill) {
                    for (let i = 1; i <= level; i++) {
                        totalPoints += skill.cost(i);
                    }
                }
            });
        });
        return totalPoints;
    }
    
    closeSkillTree() {
        console.log('🚪 关闭技能树');
        const skillMenu = document.getElementById('skillTreeMenu');
        if (skillMenu) {
            skillMenu.classList.add('hidden');
            console.log('✅ 技能树菜单已隐藏');
        } else {
            console.error('❌ 找不到技能树菜单元素');
        }
        
        // 显示主菜单
        const startMenu = document.getElementById('startMenu');
        if (startMenu) {
            startMenu.classList.remove('hidden');
            console.log('✅ 主菜单已显示');
        } else {
            console.error('❌ 找不到主菜单元素');
        }
    }
}

// 全局实例 - 在main.js中初始化
// window.weaponEnhancement = new WeaponEnhancementSystem();

console.log('武器强化系统类已加载');